package com.clwl.supervise.superviseapp.controller.base;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.risk.JgSentiment;
import com.clwl.supervise.superviseapp.entity.supervise.AdsBaobShareSupTaskDetailEntity;
import com.clwl.supervise.superviseapp.entity.supervise.JgClassifySpsc;
import com.clwl.supervise.superviseapp.entity.supervise.JgDocTemplate;
import com.clwl.supervise.superviseapp.mapper.base.JgTianjinPoiMapper;
import com.clwl.supervise.superviseapp.mapper.base.SysConfigMapper;
import com.clwl.supervise.superviseapp.entity.vo.JgClassifySpscVo;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

/**
 * 查询一些基础数据
 */
@RestController
@RequestMapping("base")
public class BaseDataController {

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private SysConfigMapper configMapper;

    @Resource
    private JgTianjinPoiMapper jgTianjinPoiMapper;


    /**
     * 查询监管环节列表
     * @param typeWhite  检查环节指定查询列表,空的话查询所有
     * @return
     */
    @GetMapping("/processCodeList")
    public ResultEntity<List<JgProcessCode>> processCodeList(String typeWhite){
        List<JgProcessCode> processCodeList = baseDataService.selectProcessCodeList(typeWhite);
        return ResultEntity.success(processCodeList);
    }


    /**
     * 通过监管环节获取业态列表
     * @param processId  环节ID
     * @param code  环节编号
     * @return
     */
    @GetMapping("/getBusinessFormatList")
    public ResultEntity< List<Map<String,Object>>> getBusinessFormatList(String processId,String code,String  parentId){
        List<Map<String,Object>> businessFormatList = baseDataService.getBusinessFormatList(processId,code,parentId);
        return ResultEntity.success(businessFormatList);
    }

    /**
     * 获取监管人员列表
     *
     * @return
     */
    @GetMapping("/getSupervisePersonList")
    public ResultEntity<List<TsUser>> getSupervisePersonList(){
        List<TsUser> businessFormatList = baseDataService.getSupervisePersonList();
        return ResultEntity.success(businessFormatList);
    }




    /**
     * 企业风险提示信息
     *
     * @param companyId
     * @return
     */
    @GetMapping("/getCompanyRiskInfo")
    public ResultEntity< Map<String,String>> getCompanyRiskInfo(Long companyId){
        Map<String, String> riskMap = baseDataService.riskInfo(companyId);
        return ResultEntity.success( riskMap);
    }


    /**
     * 企业风险提示详情
     * @param companyId  企业id
     * @param riskType 风险类型 0-食品安全；1-投诉举报；2-信用风险；3-舆情风险；4-主体资格；5-其他风险
     * @return
     */
    @GetMapping("/getRiskInfo")
    public ResultEntity<List<Map<String,Object>>> getRiskInfo(Long companyId,String riskType){
    	List<Map<String,Object>> riskInfoList = new ArrayList<Map<String,Object>>();
        TcCompany company = baseDataService.getCompanyInfo(companyId);
        switch (riskType) {

            case "0":
                //主体资格
                Map<String, Object> licenseMap = baseDataService.getLicenseByCompanyId(companyId);
                if(licenseMap == null || licenseMap.isEmpty() || licenseMap.get("YXQZ") == null){
                    licenseMap.put("picList", new ArrayList<>());
                    riskInfoList.add(licenseMap);
                    return ResultEntity.success( riskInfoList);
                }
                String yxqz = licenseMap.get("YXQZ").toString().replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", "-");
                //与当前提起做对比
                long day = DateUtil.betweenDay(new Date(), DateUtil.parse(yxqz, "yyyy-MM-dd"), true);
                if(day < 0) {
                    licenseMap.put("text","许可证"+licenseMap.get("LICENSE")+"已"+(licenseMap.get("YXQZ")== null ? "":"于"+licenseMap.get("YXQZ"))+"过期！");
                } else  if(day < 60) {
                    licenseMap.put("text","许可证"+licenseMap.get("LICENSE")+"将于"+(licenseMap.get("YXQZ")== null ? "两个月内":licenseMap.get("YXQZ"))+"过期！");
                }
                licenseMap.put("picList", new ArrayList<>());
                riskInfoList.add(licenseMap);
                return ResultEntity.success( riskInfoList);
            case "1":
                //主体标注
            	Map<String,Object> inspectMap2 = new HashMap<String,Object>();
            	inspectMap2.put("text", company.getLngLat() == null ?  "主体还未进行标注" : "主体已标注");
            	inspectMap2.put("picList", new ArrayList<>());
            	riskInfoList.add(inspectMap2);
                return ResultEntity.success( riskInfoList);
            case "2":
                //抽检信息
                Map<String, Object> chouyangMap = baseDataService.getChouyangByLicense(company.getLicense(),company.getCreditCode());
                chouyangMap.put("text","于"+chouyangMap.get("cjrq")+",抽样检测"+chouyangMap.get("ypmc")+"不合格！"+(chouyangMap.get("scjggjxdrq") == null ? "" : chouyangMap.get("scjggjxdrq"))+chouyangMap.get("jyjg"));
                chouyangMap.put("picList", new ArrayList<>());
                riskInfoList.add(chouyangMap);
                return ResultEntity.success( riskInfoList);
            case "3":
                //处罚信息
            	Map<String,Object> inspectMap4 = new HashMap<String,Object>();
            	if(companyId == 816349L) {
            		inspectMap4.put("text","处罚日期：2023-11-20，由于许可证过期长期未整改。");
            	}else {
            		inspectMap4.put("text","");
            	}
            	
            	inspectMap4.put("picList", new ArrayList<>());
            	riskInfoList.add(inspectMap4);
                return ResultEntity.success( riskInfoList);
            case "4":
                //投诉举报
                Map<String,Object> inspectMap5 = new HashMap<String,Object>();
                if(companyId == 816349L) {
                	inspectMap5.put("text","投诉日期：2023-09-11，投诉内容：售卖的饮料过期。");
                }else {
                	inspectMap5.put("text","");
                }
                
                inspectMap5.put("picList", new ArrayList<>());
                riskInfoList.add(inspectMap5);
                return ResultEntity.success( riskInfoList);
            case "5":
                //舆情风险
                 List<JgSentiment>  sentimentList = baseDataService.selectSentimentList(company);
                for (JgSentiment jgSentiment : sentimentList) {
                    Map<String,Object> inspectMap6 = new HashMap<String,Object>();
                    inspectMap6.put("text",jgSentiment.getContent());
            	    riskInfoList.add(inspectMap6);
                }
                return ResultEntity.success( riskInfoList);
            case "6":
                //包保风险
                 List<AdsBaobShareSupTaskDetailEntity>  baobaoRisk = baseDataService.getBaobaoRisk(company);
                for (AdsBaobShareSupTaskDetailEntity baobShareSupTaskDetail : baobaoRisk) {
                    Map<String,Object> inspectMap6 = new HashMap<String,Object>();
                    inspectMap6.put("text",baobShareSupTaskDetail.getTaskStress() + "-"+ baobShareSupTaskDetail.getTaskConcrete() +"选项检查未通过!");
                    riskInfoList.add(inspectMap6);
                }
                return ResultEntity.success( riskInfoList);
            default:
            	Map<String,Object> inspectMap7 = new HashMap<String,Object>();
            	inspectMap7.put("text","");
            	inspectMap7.put("riskId", new ArrayList<>());
            	riskInfoList.add(inspectMap7);
                return ResultEntity.success( riskInfoList);
        }
    }

    /**
     * 获取文书模板列表
     */
    @GetMapping("/getDocTemplateList")
    public ResultEntity<List<JgDocTemplate>> getDocTemplateList(){
        List<JgDocTemplate> templateList = baseDataService.getDocTemplateList();
        return ResultEntity.success(templateList);
    }

    /**
     * 获取文书模板详情
     * @param templateId 模板ID
     */
    @GetMapping("/getDocTemplateInfo")
    public ResultEntity<String> getDocTemplateInfo(Long templateId){
        String template = baseDataService.getDocTemplateInfo(templateId);
        return ResultEntity.success(template);
    }


    /**
     * 根据企业id，通过规则进行排序，获取路线规划
     * @param companyIds 企业id
     * @param type 1-按时限，2-按受处罚、历史检查发现问题，3-按风险高低
     * @param checktype 检查类型；1-日常检查；2-双随机检查；3-飞行检查；4-体系检查
     * @param pointLat 用户当前定位
     * @param pointLng 用户当前定位
     */
    @GetMapping("/routePlanList")
    public ResultEntity<List<Map<String,Object>>> routePlanList(String companyIds,String type,String checktype,String pointLat,String pointLng){
        List<Map<String,Object>> templateList = baseDataService.getRoutePlanList(companyIds,type,checktype,pointLat, pointLng);
        return ResultEntity.success(templateList);
    }


    /**
     * 获取各任务项代办数量
     */
    @GetMapping("/getTaskCountStatistics")
    public ResultEntity<Map<String,Object>> getTaskCountStatistics(String type){
        Map<String, Object> result= new HashMap<>();

         if(StringUtils.equals("choujian",type)) {
             result = baseDataService.getChouyangByThisYear();
         } else {
             result = baseDataService.getTaskCountStatistics(type);
         }
        return ResultEntity.success(result);
    }


    /**
     * 修改主体坐标信息
     */
    @PostMapping("/editCompanyPoint")
    public ResultEntity<String> editCompanyPoint(Long companyId ,String lat ,String lng){
          baseDataService.editCompanyPoint(companyId,lat,lng);
        return ResultEntity.success("保存成功");
    }

    /**
     * 所有企业的坐标转换
     */
    public ResultEntity<String> pointConversion(){
          baseDataService.pointConversion();
        return ResultEntity.success("保存成功");
    }


    @PostMapping("uploadCheckTest")
    public ResultEntity uploadCheckTest(  MultipartFile file){
        try {
            FileResultEntity check =  FileUploadUtil.uploadImage(file, FileUploadEnum.risk.getPath());
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 获取检查范围距离
     * @param companyId
     * @return
     */
    @PostMapping("checkDistance")
    public ResultEntity checkDistance(String companyId){
        try {
            JgPointDistance distance =  baseDataService.getCheckDistance(companyId);
            return ResultEntity.success(distance.getDistance());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 获取天地图key
     * @return
     */
    @GetMapping("getTianKey")
    public ResultEntity getTianKey(){
        try {
            SysConfigEntity key =  configMapper.queryByKey("PC_TDDT_KEY");
            return ResultEntity.success(key.getParamValue());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询二级环节列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/queryJgProcessCodeTwo", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity queryJgProcessCodeTwo() {

        try {
            //spsc：目前只查询食品生产
            String parentCode = "spsc";
            JgProcessCode jgProcessCode = baseDataService.findJgProcessCodeByCode(parentCode);
            //食品生产环节
            if ("spsc".equals(parentCode)) {
                JgClassifySpsc jgClassifySpsc = new JgClassifySpsc();
                jgClassifySpsc.setProcessId(jgProcessCode.getId());
                jgClassifySpsc.setIsTs("0");
                jgClassifySpsc.setClassifyLevel("1");
                List<JgClassifySpscVo> jgClassifySpscList = baseDataService.findClassifySpscList(jgClassifySpsc);
                return ResultEntity.success(jgClassifySpscList);
            }
            //特殊食品生产环节
            if ("tssc".equals(parentCode)) {
                JgClassifySpsc jgClassifySpsc = new JgClassifySpsc();
                jgClassifySpsc.setProcessId(jgProcessCode.getId());
                jgClassifySpsc.setIsTs("1");
                jgClassifySpsc.setClassifyLevel("1");
                List<JgClassifySpscVo> jgClassifySpscList = baseDataService.findClassifySpscList(jgClassifySpsc);
                return ResultEntity.success(jgClassifySpscList);
            }
            return ResultEntity.error("环节详细列表不存在!");
        } catch (Exception e) {
            return ResultEntity.error("环节详细列表获取失败!");
        }
    }

    /**
     * 查询天津poi数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/queryPOIByName", method = RequestMethod.GET)
    @ResponseBody
    public ResultEntity<List<JgTianjinPoi>> queryPOIByName(String name) {
        try {
            QueryWrapper<JgTianjinPoi> tianjinPoiQueryWrapper = new QueryWrapper<>();
            tianjinPoiQueryWrapper.like("name","%"+name+"%");
            List<JgTianjinPoi> list=  jgTianjinPoiMapper.selectList(tianjinPoiQueryWrapper);
            return ResultEntity.success(list);
        } catch (Exception e) {
            return ResultEntity.error("获取信息失败!");
        }
    }


}
